package vashion.azeroth.api.controller.item;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import vashion.azeroth.api.annotation.Auth;
import vashion.azeroth.api.controller.base.BaseController;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.ForestErrorEnum;
import vashion.azeroth.core.item.pojo.ForestDO;
import vashion.azeroth.core.item.pojo.ForestTreeDO;
import vashion.azeroth.core.manager.forest.BaseForestManager;
import vashion.azeroth.core.result.ApiResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/forest")
public class ForestController<T> extends BaseController {

    private final static Logger log = LoggerFactory.getLogger(ForestController.class);

    @Autowired
    private BaseForestManager baseForestManager;

    @RequestMapping("getForestDetail.htm")
    @ResponseBody
    public ApiResult<ForestDO> getForestDetail(long forestId) {

        if (forestId <= 0) {
            return ApiResult.newErrorResult(ForestErrorEnum.ARG_ERROR.getErrorCode(), ForestErrorEnum.ARG_ERROR.getErrorMessage());
        }
        return baseForestManager.getDetail(forestId);
    }


    /**
     * 获取完整类目树
     *
     * @return
     */
    @RequestMapping("getForestTree.htm")
    @ResponseBody
    public ApiResult<List<ForestTreeDO>> getForestTree() {

        ApiResult<Map<ForestDO, List<ForestDO>>> result = baseForestManager.getForestTree();
        if (!result.isSuccess()) {
            return ApiResult.newErrorResult(ForestErrorEnum.SYSTEM_ERROR.getErrorCode(), ForestErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
        Map<ForestDO, List<ForestDO>> forestDOListMap = result.getData();
        List<ForestTreeDO> forestTreeDOList = new ArrayList<ForestTreeDO>();
        for (Map.Entry<ForestDO, List<ForestDO>> entry : forestDOListMap.entrySet()) {

            ForestDO parent = entry.getKey();
            if (AzerothConstants.ItemForest.NORMAL == parent.getStatus()) {
            	ForestTreeDO forestTreeDO = new ForestTreeDO();
                forestTreeDO.setParentDO(parent);
                forestTreeDO.setChildList(entry.getValue());
                forestTreeDOList.add(forestTreeDO);
            }
        }
        return ApiResult.newSuccessResult(forestTreeDOList);
    }

    /**
     * 获取完整类目树
     *
     * @return
     */
    @RequestMapping("getForestList.htm")
    @ResponseBody
    public ApiResult<List<ForestDO>> getForestList(@ModelAttribute("forestDO") ForestDO forestDO) {
    	forestDO.setStatus(AzerothConstants.ItemForest.NORMAL);
        return baseForestManager.getForestList(forestDO);
    }

}
